//
// Created by wuji on 2020/5/18.
//

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "server.h"

//构造方法，给出port参数
socket_server::socket_server(int port) {
	this->port = port;
}

//创建服务端 listen fd
bool socket_server::create() {
	if (this->port==0){
		throw "server server port can't be 0";
	}
	struct sockaddr_in server_addr;
	this->server_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (this->server_fd==-1){
		throw "server server port can't be 0";
	}
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(this->port);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bind(this->server_fd,(struct sockaddr *)&server_addr,sizeof(server_addr)) != 0 ){
		close(this->server_fd);
		this->server_fd=0;
		printf("%s","fail");
		return false;
	}

	if (listen(this->server_fd,30)!=0){
		printf("%s","fail1");
		return false;
	}
	return true;
}


int socket_server::Accept() {
	int client_fd =accept(this->server_fd,0,0);
	return client_fd;

}

int socket_server::Recv(const int clientfd,char *buf, const int buflen) {
	int cnt = recv(clientfd,buf,buflen,0);
	return cnt;
}

int socket_server::Send(const int clientfd,char *buf,const int buflen){
	int cnt = send(clientfd,(char *)buf,buflen,0);
	if (cnt<=0){
		printf("server send fail");
		return -1;
	}

	return cnt;
}